/**
 * request 网络请求工具
 * 更详细的 api 文档: https://github.com/umijs/umi-request
 */
import { extend, RequestOptionsInit as UmiRequestOptionsInit, ResponseError } from 'umi-request';
import { notification, Modal, message } from 'antd';
import { formatMessage, history as router } from 'umi';
import { ShowType } from '../common/constants';

export interface PageRequest {
  page?: number;
  pageSize?: number;
  all?: boolean;
}
export interface Response<T> {
  msg: string;
  code: number;
  data: T;
}

export interface PageData<T> {
  docs: T[];
  limit: number;
  page: number;
  pages: number;
  total: number;
}



/**
 * 业务错误处理
 * code 为非0值时处理
 */

export interface IRequestOptionsInit extends RequestOptionsInit {
  showType?: ShowType;
}

// let resolveErrorFlag = false;
// request.interceptors.response.use(async (response, options: IRequestOptionsInit) => {

// });


/**
 * 异常处理程序
 */
const errorHandler = (error: ResponseError) => {
  const { response = {}, message = '', data = {} } = error;
  const { status = 500 } = response ?? {};
  if (message === 'http error' && status === 500) {
    return data; // 对 status 为 500 的接口也返回 data
  }
}

/**
 * 配置request请求时的默认参数
 */
const request = extend({
  errorHandler, // 默认错误处理
  credentials: 'include', // 默认请求是否带上cookie
  headers: {
    _shop: '1'
  },
});

export interface RequestOptionsInit extends UmiRequestOptionsInit {
  showType?: ShowType;
}


request.interceptors.request.use((url, options) => {

  if (url.includes('https://')) {
    return {
      url,
      options
    }
  }
  return {
    url,
    options: {
      ...options,
      headers: {
        Authorization: `Bearer ${sessionStorage.getItem('__TOKEN__')}`
      }
    }
  }
})
/**
 * 处理国际化消息
 * @param {Response<T>} res - 接口返回数据
 * @param {function|object} placeholderVales - 处理国际化占位符
 * @returns {string} 处理过的消息
 * @todo 处理成功的消息，但是目前对于成功消息暂时还没有想到合适的办法
 */
export function i18nMsg<T>(
  res: Response<T>,
  placeholderVales?: (data: Response<T>) => { [key: string]: any } | { [key: string]: any },
): string {
  const { code, data } = res;
  let { msg } = res;
  if (code !== 0) {
    msg = formatMessage(
      {
        id: `error.server.${code}`,
        defaultMessage: msg,
      },
      typeof placeholderVales === 'function'
        ? placeholderVales(res)
        : placeholderVales || data || {},
    );
  }
  return msg;
}

let resolveErrorFlag = false;
request.interceptors.response.use(async (response, options: RequestOptionsInit) => {
  const { status } = response;
  if (status >= 200) {
    const data = await response.clone().json();
    const {
      msg,
      code,
    }: {
      msg: string;
      showType: number;
      code: number;
    } = data || {};

    // if(options.)
    // 未登录特殊处理
    if (code === 10004) {
      window.location.href = `/login?redirect=${window.location.href || ''}`;
      throw Error('401 Unauthorized');
    }

    // 当 code 为 0时并且又有 msg 时，表示需要提示成功信息
    // 成功信息强制采用 antd.message.success
    // 这样一来，showType 就被定义为了错误提示类型
    const showType =
      (code === 0 ? ShowType.MESSAGE_SUCCESS : null) ||
      options.showType ||
      data.showType ||
      ShowType.NOTIFICATION_ERROR;

    if (!resolveErrorFlag && msg && showType !== ShowType.NONE) {
      resolveErrorFlag = true;

      const content = msg || '发生未知错误，请稍后重试！';
      const openAlert = (type: string) => {
        Modal[type]({
          title: '通知',
          content,
        });
      };
      const openNotification = (type: string) => {
        notification[type]({
          message: '通知',
          description: content,

        });
      };
      const openMessage = (type: string) => {
        message[type](content, 5);
      };

      switch (showType) {
        case ShowType.ALERT_ERROR:
          openAlert('error');
          break;
        case ShowType.ALERT_WARNING:
          openAlert('warning');
          break;
        case ShowType.ALERT_SUCCESS:
          openAlert('success');
          break;
        case ShowType.ALERT_INFO:
          openAlert('info');
          break;
        case ShowType.NOTIFICATION_ERROR:
          openNotification('error');
          break;
        case ShowType.NOTIFICATION_WARNING:
          openNotification('warning');
          break;
        case ShowType.NOTIFICATION_SUCCESS:
          openNotification('success');
          break;
        case ShowType.NOTIFICATION_INFO:
          openNotification('info');
          break;
        case ShowType.MESSAGE_ERROR:
          openMessage('error');
          break;
        case ShowType.MESSAGE_WARNING:
          openMessage('warning');
          break;
        case ShowType.MESSAGE_SUCCESS:
          openMessage('success');
          break;
        case ShowType.MESSAGE_INFO:
          openMessage('info');
          break;
        default:
          break;
      }

      // 1秒内多个错误请求不再弹出提示
      setTimeout(() => {
        resolveErrorFlag = false;
      }, 1000);
    }
  }

  return response;
});

window.requestIdx = request
export default request;
